<template>
  <div class="left_box">
    <div class="tree_title">
      <div class="title">角色列表</div>
      <Button
        type="primary"
        @click="editRole()"
      >新建角色</Button>
    </div>

    <!-- <Input
      v-model="searchValue"
      placeholder="请输入关键字"
      clearable
      @on-change="searchChange"
    /> -->

    <List>
      <ListItem
        v-for="item in roleGather"
        :key="item.id"
        class="role-row"
        :class="{
          active: roleId === item.id
        }"
        @click="selectRole(item)"
      >
        <Icon
          type="ios-person"
          color="#458ef7"
          size="18"
        />
        <span>{{item.name}}</span>
      </ListItem>
    </List>
  </div>

  <edit-dialog
    ref="editDialogRef"
    v-if="editDialogDisplay"
    @submit="editSuccess"
    @cancel="editDialogDisplay = false"
  />
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, inject, watch, nextTick } from 'vue'

import { roleList } from '@/api/modules/role'
import EditDialog from './components/EditDialog.vue'

// import 'element-plus/theme-chalk/el-tree.css'

const emit = defineEmits(['selected'])

const roleGather = ref([])

const searchValue = ref('')
const treeRef = ref(null)

const editDialogDisplay = ref(false)

const getRoleList = (reset) => {
  return roleList().then(({data}) => {
    roleGather.value = data

    if(data.length && reset) {
      selectRole(data[0])
    }
  })
}

const searchChange = () => {}

const roleId = ref(null)
const selectRole = data => {
  roleId.value = data.id
  emit('selected', data)
}

const editDialogRef = ref(null)
const editRole = (isEdit) => {
  editDialogDisplay.value = true

  if(!isEdit) return
  nextTick(()=>{
    const rowRole = roleGather.value.find(item=> item.id === roleId.value)
    editDialogRef.value.initDialog(rowRole)
  })
}

const editSuccess = (id) => {
  editDialogDisplay.value = false

  getRoleList().then(()=>{
    if(!id) return

    const rowRole = roleGather.value.find(item=> item.id === id)

    selectRole(rowRole)
  })

  
}

onMounted(() => {
  getRoleList(true)
})

defineExpose({
  editRole,
  getRoleList
})
</script>

<style scoped lang="scss">
.ivu-list {
  height: calc(100% - 50px);
  overflow-y: auto;
}
.role-row {
  cursor: pointer;
  &.active {
    color: #4a8ae9;
    font-weight: bold;
  }
}
</style>
